<?php

use think\facade\Db;
use app\common\model\Config;

//保留两位小数，不四舍五入，自动补零
function sprintfFloor($value)
{
    return sprintf("%.2f", floor($value * 100) / 100);
}

function releaseState($key = '')
{
    $arr = array(
        1 => '释放中',
        2 => '释放完成'
    );
    if ($key) {
        return $arr[$key];
    }

    return $arr;
}

function contractRole($key = '')
{
    $arr = array(
        0 => '',
        1 => '加盟商',
        2 => '合约会员',
    );
    if ($key) {
        return isset($arr[$key]) ? $arr[$key] : '-';
    }

    return $arr;
}

function carouselType($key = '')
{
    $arr = array(
        1 => '首页轮播',
        2 => '',
        3 => '',
        4 => '',
        5 => '',
    );
    if ($key) {
        return $arr[$key];
    }

    return $arr;
}

function newsType($key = '')
{
    $arr = array(
        1 => '新闻',
        2 => '公告'
    );
    if ($key) {
        return $arr[$key];
    }

    return $arr;
}

function newsPosition($key = '')
{
    $arr = array(
        1 => '系统',
        2 => '',
        3 => '',
        4 => '',
        5 => '',
    );
    if ($key) {
        return $arr[$key];
    }

    return $arr;
}

function pastureRebateState($key = '')
{
    $arr = array(
        1 => '返还中',
        2 => '返还完成'
    );
    if ($key) {
        return $arr[$key];
    }

    return $arr;
}

function courseType($key = '')
{
    $arr = array(
        'image_text' => '图文',
        'video'      => '视频',
        'audio'      => '音频'
    );
    if ($key) {
        return $arr[$key];
    }

    return $arr;
}

function courseIsFree($key = '')
{
    $arr = array(
        1 => '免费',
        2 => '付费'
    );
    if ($key) {
        return $arr[$key];
    }

    return $arr;
}

function getCount($fetchSql)
{
    $fetchSql = "SELECT count(*) as tp_count " . strstr($fetchSql, "FROM");
    $fetchSql = strstr($fetchSql, 'ORDER', true);
    return Db::query($fetchSql)[0]['tp_count'];
}

function get_pay_way($value)
{
    switch ($value) {
        case "":
            return '未支付';
        case "bank":
            return '银行卡';
        case "wechat":
            return '微信';
        case "alipay":
            return '支付宝';
        case "behalf":
            return '找好友代付';
        case "deduct":
            return '抵扣';
        case "village_bao_fen":
            return "云宝+云分";
        default:
            $assets = \app\common\model\Assets::getFields(3);
            return $assets[$value];
    }
}

/**
 * @param $value
 * @param $type
 * @return string|string[]
 * 主商城订单状态
 */
function getProductOrderStatus($value, $type = 1)
{
    $status = [1 => '待付款', 2 => '待发货', 3 => '待收货', 4 => '待评价', 5 => '已完成', 6 => '待核销', 7 => '已取消', 11 => '已托管', 12 => '待自提'];
    return $type == 1 ? (isset($status[$value]) ? $status[$value] : '已退款')  : $status;
}

//1等待商家同意，2寄回商品，3等待商家确认4退款成功5未通过申请
function getOrderRefundStatus($value, $type = 1)
{
    $status = [1 => '等待商家同意', 2 => '寄回商品', 3 => '等待商家确认', 4 => '退款成功', 5 => '未通过申请'];
    return $type == 1 ? (isset($status[$value]) ? $status[$value] : '未知状态')  : $status;
}

/**
 * @param $value
 * @return string
 * 主商城订单详情友好提示
 */
function getProductOrderFriendly($value, $order_way=1)
{
    $status = [
        1 => '商品待付款',
        2 => '商品已付款，等待卖家发货',
        3 => '商家已发货，等待确认收货',
        4 => '已确认收货，等待评价',
        5 => '交易已完成',
        6 => '已下单，等待核销',
        11 => '已托管'
    ];
    if($order_way == 2 && $value == 4){
        return '已核销';
    }else{
        return $value ? $status[$value] : '';
    }
}

function getProductOrderType($value)
{
}

//订单状态1待付款2待发货3待收货4待评价5已完成6待核销7已取消
function getOrderStatus($value, $type = 1)
{
    if ($type == 1) {
        switch ($value) {
            case 1:
                return '待付款';
            case 2:
                return '待发货';
            case 3:
                return '待收货';
            case 4:
                return '待评价';
            case 5:
                return '已完成';
            case 6:
                return '待核销';
            case 7:
                return '已取消';
            case 11:
                return '已托管';
            case 12:
                return '待自提';
            default:
                return '其他';
        }
    } else {

        return [1 => '待付款', 2 => '待发货', 3 => '待收货', 4=>'待评价', 5 => '已完成', 6 => '待核销', 7 => '已取消', 11 => '已托管', 12 => '待自提'];
    }
}

/**
 * @param $value
 * @return array
 * 原点 2023年1月7日15:23:24 获取支付方式
 */
function getPaymentMethod($value)
{
    $method = [];
    foreach (explode(',', $value) as $item) {
        $method[] = [
            'title'           => get_pay_way($item),
            'pay_way'         => $item,
            'icon'            => '/static/api/img/' . $item . '.png',
            'is_pay_password' => in_array($item, ['alipay', 'wechat', 'behalf']) ? 0 : 1
        ];
    }
    return $method;
}

function getOperation($name)
{
    switch ($name) {
        case "save":
            return '修改';
        case "create":
            return '新增';
        case "update":
            return '更新状态';
        case "updateAll":
            return '批量更新状态';
        case "delete":
            return '删除';
        case "deleteAll":
            return '批量删除';
        default:
            return '操作';
    }
}

function getNotifyType($name)
{
    switch ($name) {
        case 1:
            return '订单通知';
        case 2:
            return '注册通知';
        default:
            return '系统通知';
    }
}

/**
 * 格式化字节大小
 * @param number $size 字节数
 * @param string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 */
function format_bytes($size, $delimiter = '')
{
    $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
    for ($i = 0; $size >= 1024 && $i < 5; $i++) {
        $size /= 1024;
    }
    return $size . $delimiter . $units[$i];
}


function generate($length, $prefix = '', $type = 1)
{
    if ($type == 1) {
        $code = rand(100000, 999999);
    } else {
        $chars = array('a', 'b', '1', 'd', 'e', '2', 'g', 'h',
            'i', '3', 'k', 'l', '4', 'n', 'o', '5', 'q', 'r', 's',
            't', 'u', '6', 'w', 'x', '7', 'z', 'c', '8', 'j', 'm',
            'p', 'v', 'y', 'f', '9');
        $keys = array_rand($chars, $length);
        $code = '';
        for ($i = 0; $i < $length; $i++) {
            $code .= $chars[$keys[$i]];
        }
    }

    if ($prefix) {
        $code = $prefix . $code;
    }

    $is = \app\common\model\User::where('code', $code)->count();
    if ($is) {
        return generate(6, $prefix, $type);
    } else {
        return $code;
    }

}

function generateCode($length)
{
    $chars = array('a', 'b', '1', 'd', 'e', '2', 'g', 'h',
        'i', '3', 'k', 'l', '4', 'n', 'o', '5', 'q', 'r', 's',
        't', 'u', '6', 'w', 'x', '7', 'z', 'c', '8', 'j', 'm',
        'p', 'v', 'y', 'f', '9');
    $keys = array_rand($chars, $length);
    $code = '';
    for ($i = 0; $i < $length; $i++) {
        $code .= $chars[$keys[$i]];
    }
    return $code;

}

function generateCodeD($length)
{
    $chars = array('☞', 'b', '1', '♪', 'の', '☆→', '♧', 'd', 'e', '2', 'g', 'h',
        '3', 'k', '4', '▅', '▄', '▃', 'n', '☼', '￡', '❤', '✎', 'o', '5', 'q', 'r',
        't', 'u', '▇', '▂', '▁', '6', 'w', 'x', '7', 'z', 'c', '8', 'j', 'm',
        'p', 'v', 'y', 'f', '9', '-', '/', '♦', '♦ ', '◦', '▁', '▃', '▄', '▅', '▆');
    $keys = array_rand($chars, $length);
    $code = '';
    for ($i = 0; $i < $length; $i++) {
        $code .= $chars[$keys[$i]];
    }
    return $code;

}

function handleImg($src, $http = 'https')
{
    if (empty($src)) {
        return '';
    }
    if (is_array($src)) {
        foreach ($src as &$v) {
            $v = $http . '://' . $_SERVER['SERVER_NAME'] . $v;
        }
        return $src;
    } else {
        return $http . '://' . $_SERVER['SERVER_NAME'] . $src;
    }

}

function filter_Emoji($str)
{
    $str = preg_replace_callback(    //执行一个正则表达式搜索并且使用一个回调进行替换
        '/./u',
        function (array $match) {
            return strlen($match[0]) >= 4 ? '' : $match[0];
        },
        $str);

    return $str;
}

function queryIp($ip)
{

    $url = "http://whois.pconline.com.cn/jsFunction.jsp?ip=" . $ip;
    $ch = curl_init();
    //设置选项，包括URL
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);

    //执行并获取HTML文档内容
    $output = curl_exec($ch);
    //释放curl句柄
    curl_close($ch);
    $info = iconv('GB2312', 'UTF-8', $output); //因为是js调用 所以接收到的信息为字符串，注意编码格式

    return get_between($info, "('", "',");
}

function get_between($input, $start, $end)
{
    $substr = substr($input, strlen($start) + strpos($input, $start), (strlen($input) - strpos($input, $end)) * (-1));
    return $substr;
}

function confValue($name)
{
    return Config::where('name', $name)->value('value');
}

if(!function_exists('roundNum')){
    /**
     * 舍去式保留两位小数位
     * @param $value
     * @param int $len
     * @return false|string
     */
    function roundNum($value, $len = 2)
    {
        if(strpos($value,".") == false){
            return $value;
        }else{
            return substr($value, 0, strpos($value,".")+$len+1);
        }
    }
}

function get_adcode($lng, $lat)
{
    $ad = geocoder_baidu($lng, $lat);
    $adcode = isset($ad['result']['addressComponent']['adcode']) ? $ad['result']['addressComponent']['adcode'] : 0;
    return $adcode;

}

function geocoder_baidu($lng, $lat, $ak = '')
{
    if (empty($ak)) {
        $ak = 'l0CAI5bggAqghS3wPGDWAgXUVS6SEkcp';
    }
    $url = 'http://api.map.baidu.com/reverse_geocoding/v3/?ak=' . $ak . '&output=json&coordtype=wgs84ll&location=' . $lat . ',' . $lng;
    $json = json_decode(file_get_contents($url), true);
    return $json;
}

function distance($lat1, $lon1, $lat2, $lon2) {
    // 将角度转换为弧度
    $degToRad = M_PI / 180;

    // 将经纬度转换为弧度
    $lat1 *= $degToRad;
    $lon1 *= $degToRad;
    $lat2 *= $degToRad;
    $lon2 *= $degToRad;

    // Haversine公式计算距离
    $dLat = ($lat2 - $lat1);
    $dLon = ($lon2 - $lon1);
    $a = pow(sin($dLat/2), 2) + cos($lat1) * cos($lat2) * pow(sin($dLon/2), 2);
    $c = 2 * atan2(sqrt($a), sqrt(1-$a));
    $distance = round(6371 * $c); // 单位：千米

    return $distance;
}

function wechatSign($arr, $type = 'mall')
{
    if(!in_array($type, ['mall', 'pasture'])) return '';
    $arr = array_filter($arr);
    if(isset($arr['sign'])) unset($arr['sign']);

    //$mch_key = config('pay.wechat')['mch_key'];
    $mch_key = config('pay')[$type]['JSAPI']['mch_key'];

    ksort($arr);
    $str = urldecode(http_build_query($arr));
    $str = $str . '&key=' . $mch_key;

    return strtoupper(md5($str));
}

function tillageRebateState($key = '')
{
    $arr = array(
        1 => '返还中',
        2 => '已完成'
    );
    if ($key) {
        return $arr[$key];
    }

    return $arr;
}

function villageRebateState($key = '')
{
    $arr = array(
        1 => '返还中',
        2 => '已完成'
    );
    if ($key) {
        return $arr[$key];
    }

    return $arr;
}

function isFloat($param)
{
    return is_float($param) || (is_string($param) && strpos($param, '.') !== false);
}


function is_mobile()
{
    if(isset($_SERVER['HTTP_USER_AGENT'])) {
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        $mobile_agents = Array("Android", "iPhone", "iPod", "iPad", "Windows Phone", "BlackBerry", "SymbianOS");
        foreach ($mobile_agents as $mobile_agent) {
            if (strpos($user_agent, $mobile_agent) !== false) {
                return true;
            }
        }
    }
    return false;
}

function getOs()
{
    if(isset($_SERVER['HTTP_USER_AGENT'])) {
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        if (preg_match('/iphone|ipod|ipad/i', $user_agent)) {
            return 'iOS';
        } else if (preg_match('/android/i', $user_agent)) {
            return 'Android';
        }else if (preg_match('/windows nt/i', $user_agent)) {
            return 'windows';
        }
    }

    return '';
}

/**
 * 审核状态
 */
function getExamineStatus($key = '')
{
    $arr = [
        1 => '待审核',
        2 => '已通过',
        3 => '已驳回'
    ];
    if ($key) {
        return $arr[$key];
    }

    return $arr;
}

